package com.sunny.design.proxy.dynamicproxy.cglibproxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * CGLib动态代理
 *  通过生成被代理类的子类来增强目标方法，不需要被代理类实现接口
 *
 *
 * @author Sunny
 * @date 2020/1/1 22:19
 */
public class CGLibMeiPo implements MethodInterceptor {
    public Object getInstance(Class target) {
        //相当于JDK的Proxy
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target);
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        before();
        Object invoke = methodProxy.invokeSuper(o, objects);
        after();
        return invoke;
    }


    public void before() {
        System.out.println("CGLib Proxy before method");
    }

    public void after() {
        System.out.println("CGLib Proxy after method");
    }
}
